
#include <QtCore/QCoreApplication>
#include <QtCore/QRegExp>
#include <QSqlQueryModel>
#include <QSqlQuery>
#include <QFile>
#include <QIODevice>
#include <QTextStream>

void createDataForPaper(QString page, QSqlDatabase* library);

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	QFile f("o.xml");
	if(!f.open(QIODevice::ReadOnly|QIODevice::Text))
		return 1;
	QTextStream in(&f);
	QString page = in.readAll();
	QRegExp reg = QRegExp("<page.*>(.*)</page>");
	if(reg.indexIn(page)!=-1)
		page = reg.cap(0);
	QSqlDatabase library;
	library = QSqlDatabase::addDatabase("QSQLITE","Library");
	library.setDatabaseName("PDFWorkingSpace.db");
	if(!library.open())
	{

	}
	createDataForPaper(page,&library);
	QSqlQuery query(library);

	query.exec("SELECT * FROM temp ORDER BY Font DESC");
	
	//query.exec("DROP TABLE temp");
	QSqlDatabase::removeDatabase("Library");
	return 0;
}

void createDataForPaper(QString page, QSqlDatabase* library)
{
	QRegExp reg1 = QRegExp("<font size=\"(.*)\" face=\"([^\"]*)\">(.*)</font>");
	QRegExp reg2 = QRegExp("<text x=\"(.*)\" y=\"(.*)\" width=\"(.*)\" height=\"(.*)\">(.*)</text>");
	reg1.setMinimal(true);
	reg2.setMinimal(true);
	int currentPosition = 0;
	
	QSqlQuery query(*library);
	query.exec("CREATE TABLE IF NOT EXISTS temp (id INTEGER PRIMARY KEY, Font INTEGER, Face TEXT, X INTEGER, Y INTEGER, W INTEGER, H INTEGER, X2 INTEGER, Y2 INTEGER, content TEXT)");

	while(true)
	{
		int index = reg1.indexIn(page,currentPosition);
		if(index == -1)
		{
			break;
		}
		else
		{
			currentPosition = index + reg1.matchedLength();

			int fontsize = reg1.cap(1).toInt();
			QString face = reg1.cap(2);
			QString text = reg1.cap(3);

			int currentPosition2 = 0;
			while(true)
			{
				int index2 = reg2.indexIn(text,currentPosition2);
				currentPosition2 = index2 + reg2.matchedLength();
				if(index2 == -1)
					break;
				else
				{
					int x = reg2.cap(1).toInt();
					int y = reg2.cap(2).toInt();
					int width = reg2.cap(3).toInt();
					int height = reg2.cap(4).toInt();
					QString tt = reg2.cap(5);
					query.prepare("INSERT INTO temp (Font,Face,X,Y,W,H,X2,Y2,content) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
					query.addBindValue(fontsize);
					query.addBindValue(face);
					query.addBindValue(x);
					query.addBindValue(y);
					query.addBindValue(width);
					query.addBindValue(height);
					query.addBindValue(x+width);
					query.addBindValue(y+height);
					query.addBindValue(tt);
					query.exec();
				}
			}
		}
	}
}